<?php

namespace app\admin\controller\service\order;

use addons\shopro\library\commission\Reward as RewardLibrary;
use app\common\controller\Backend;
use think\Db;
use addons\service\library\Refund;
use app\api\model\service\Order AS OrderModel;
use think\Exception;
use think\Log;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\service\order\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\service\order\Order;
        $this->view->assign("traveltypeList", $this->model->getTraveltypeList());
        $this->view->assign("chooseSkillTypeList", $this->model->getChooseSkillTypeList());
        $this->view->assign("paytypeList", $this->model->getPaytypeList());
        $this->view->assign("toShopList", $this->model->getToShopList());
        $this->view->assign("isServiceList", $this->model->getIsServiceList());
        $this->view->assign("isComplaintList", $this->model->getIsComplaintList());
        $this->view->assign("isPoolList", $this->model->getIsPoolList());
        $this->view->assign("isSettleList", $this->model->getIsSettleList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("order_count", Db::name("service_order")->where("status",1)->count("id"));
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        foreach ($list as &$val)
        {
            $val->user = db('user')->where('id',$val->user_id)->field('avatar,nickname,mobile')->find();
            $val->address = db('service_order_address')->where('order_id',$val->id)->field('name,sex,mobile,province,city,district,area,address')->find();
            $val->detail = db('service_order_detail')->where('order_id',$val->id)->field('name,image,sku_name,num,price,sumprice')->find();
            $val->skill = $val->skill_id?db('service_skill')->field('name,mobile,image')->where('id',$val->skill_id)->find():'';
            $val->shop = $val->shop_id?db('service_shop')->where('id',$val->shop_id)->field('name,abbr,logo_image,leader_name,leader_mobile')->find():'';
            $val->skillRebate = $val->is_settle == 2?db('service_rebate')->where(['order_id'=>$val->id,'type'=>0])->sum('num'):0.00;
            $val->shopRebate = $val->is_settle == 2?db('service_rebate')->where(['order_id'=>$val->id,'type'=>1])->sum('num'):0.00;
            $val->create_time = date("Y-m-d H:i:s",$val->createtime);
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    public function info($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->reach_images = $row->reach_images?explode(',',$row->reach_images):'';
        $row->before_images = $row->before_images?explode(',',$row->before_images):'';
        $row->finish_images = $row->finish_images?explode(',',$row->finish_images):'';
        //地址,项目,技师,商户,附加项目,补差价
        $user = db('user')->where('id',$row->user_id)->field('avatar,nickname,mobile')->find();
        $shop = $row->shop_id?db('service_shop')->field('name,leader_mobile,province,city,district,address')->where('id',$row->shop_id)->find():'';
        $skill = $row->skill_id?db('service_skill')->field('name,mobile,image,province,city,district,address')->where('id',$row->skill_id)->find():'';
        $address = db('service_order_address')->field('name,sex,mobile,province,city,district,area,address')->where('order_id',$ids)->find();
        $detail = db('service_order_detail')->field('name,image,sku_name,num,price,sumprice')->where('order_id',$ids)->find();
        $addList = \app\api\model\service\AddOrder::getOrderDetailList($ids);
        $premiumList = db('service_premium_order')->field('paytype,orderId,payprice,paytime')->where(['order_id'=>$ids,'state'=>1])->select();
        $logList = db('service_order_log')->field('type,content,createtime')->where(['order_id'=>$ids])->order('id desc')->select();
        $skillRebate = $row->is_settle == 2?db('service_rebate')->where(['order_id'=>$row->id,'type'=>0])->sum('num'):0.00;
        $shopRebate = $row->is_settle == 2?db('service_rebate')->where(['order_id'=>$row->id,'type'=>1])->sum('num'):0.00;
        $this->view->assign([
            'user'=>$user,
            'skillRebate'=>$skillRebate,
            'shopRebate'=>$shopRebate,
            'order'=>$row,
            'to_shop'=>$row->to_shop,
            'shop'=>$shop,
            'skill'=>$skill,
            'address'=>$address,
            'detail'=>$detail,
            'addList'=>$addList,
            'premiumList'=>$premiumList,
            'logList'=>$logList
        ]);
        return $this->view->fetch();
    }


    public function updateskill($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->status > 2 && $this->error('当前服务人员已出发,无法更换服务者');
        $row->to_shop == 'shop' && $this->error('到店核销订单无需更换服务者');
        if($this->request->isPost()){
            $params = input('post.');
            $skill = \app\admin\model\service\skill\Skill::where('id',$params['skill_id'])->field('id,shop_id,user_id')->find();
            $order =  \app\admin\model\service\order\Order::where('id',$params['id'])->field('id,user_id,to_shop,starttime,actendtime,goods_id')->find();
            $exist = \app\api\model\service\SkillTime::where(['skill_id'=>$skill['id'],'state'=>['in',[1,2]],'starttime'=>['between',[$order['starttime'],$order['actendtime']]]])->value('id');
            //$exist && $this->error('当前项目时间区间有被预约');
            $update['skill_id'] = $skill['id'];
            if($row->is_pool == 1)
            {
                $update['is_pool'] = 0;
            }
            if($skill['shop_id'])
            {
                $update['shop_id'] = $skill['shop_id'];
            }
            db('service_order')->where('id',$params['id'])->update($update);
            \app\api\model\service\SkillTime::updateSkillTime(['skill_id'=>$params['skill_id'],'starttime'=>$order['starttime'],'actendtime'=>$order['actendtime']],1);
            db('service_order_log')->insert(['order_id'=>$ids,'user_id'=>$row->user_id,'type'=>16,'content'=>'平台已分配服务者','createtime'=>time()]);
            $skillOpenid = \app\api\model\service\UserInfo::getOpenid($params['skill_id'],1);
            \app\api\model\service\Order::createOrderTemplateParams(['id'=>$params['id'],'user_id'=>$order['user_id'],'to_shop'=>$order['to_shop'],'type'=>1,'templateAttr'=>'skill_order_template','openid'=>$skillOpenid]);

            /// ///通知信息
            $data = Db::name("service_project_configure")->find();

            $appId = $data['skillappid'];//服务端appid

            $addre_data = Db::name("service_order_address")->where(['order_id'=>$params['id']])->find();
            $goods_data = Db::name("service_goods")->where(['id'=>$order['goods_id']])->find();
            $send_user_data = Db::name("service_user_info")->where(['user_id'=>$skill['user_id']])->find();

            $address = $addre_data['province']. $addre_data['city']. $addre_data['district']. $addre_data['address'];
            $param = [
                'touser'      => $send_user_data['mp_openid'],
                'template_id' => 'AGtv9bG6Njf4Ruc-nAYvg2bQSXCe8tmx0L88TY8MoJ4',
                'miniprogram' => [
                    'appid'    => $appId,
                    'path' => ''
                ],
                'data'        => [
                    'thing12'  => [
                        'value' => mb_substr($goods_data['name'], 0, 20),
                    ],
                    'time13' => [
                        'value' => date('Y年n月j日 H:i:s',$order['starttime']),
                    ],
                    'thing8' => [
                        'value' => $addre_data['name'],
                    ],

                    'phone_number9' => [
                        'value' => $addre_data['mobile'],
                    ],
                    'thing11' => [
                        'value' => mb_substr($address, 0, 20),
                    ]
                ]
            ];
            try {
                \app\common\model\User::sendTplMsg($param);
                $msg = '推送成功';
            } catch (\Exception $e) {
                $msg = $e->getCode() == '43004' ? '没有关注该服务号' : $e->getMessage();
            }
            Log::write("分配服务人员：".json_encode($param)."__appid_data:".json_encode($msg));


            $this->success('分配成功');
        }
        $map['state'] = 1;
        $map['city'] = $row->city;
        $map[] = ['exp', Db::raw("FIND_IN_SET('$row->goods_id',goods_ids)")];
        if($row->shop_id)
        {
            $map['shop_id'] = $row->shop_id;
        }
        $list = \app\admin\model\service\skill\Skill::where($map)->field('id,name')->select();


        $this->assign(['id'=>$ids,'skillList'=>$list]);
        return $this->view->fetch();
    }


    public function updateshop($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->status > 1 && $this->error('当前服务人员已出发,无法更换商户');
        $row->to_shop == 'shop' && $this->error('到店核销订单无需更换商户');
        if($this->request->isPost()){
            $params = input('post.');
            $shopId = \app\admin\model\service\skill\Shop::where('id',$params['shop_id'])->value('id');
            $order =  \app\admin\model\service\order\Order::where('id',$params['id'])->field('id,user_id,to_shop')->find();
            db('service_order')->where('id',$params['id'])->update(['shop_id'=>$shopId,'is_pool'=>0]);
            db('service_order_log')->insert(['order_id'=>$ids,'user_id'=>$row->user_id,'type'=>14,'content'=>'平台已分配商户','createtime'=>time()]);
            $shopOpenid = \app\api\model\service\UserInfo::getOpenid($params['shop_id'],2);
            \app\api\model\service\Order::createOrderTemplateParams(['id'=>$order['id'],'user_id'=>$order['user_id'],'to_shop'=>$order['to_shop'],'type'=>2,'templateAttr'=>'shop_order_template','openid'=>$shopOpenid]);
            $this->success('分配成功');
        }
        $map['state'] = 1;
        $map['city'] = $row->city;
        $map[] = ['exp', Db::raw("FIND_IN_SET('$row->goods_id',goods_ids)")];
        $list = \app\admin\model\service\shop\Shop::where($map)->field('id,name')->select();
        $this->assign(['id'=>$ids,'shopList'=>$list]);
        return $this->view->fetch();
    }



    public function handleOrder()
    {
        $params = input('get.','');
        Db::startTrans();
        $order = \app\api\model\service\Order::where(['id'=>$params['ids']])->lock(true)->find();
        !in_array($order['status'],[1,2,3,4,5]) && $this->error('订单状态异常,无法操作');
        ($params['state'] == 2 && empty($order['skill_id'])) && $this->error('请先分配订单服务者');
        try{
            switch ($params['state'])
            {
                case 2:
                    OrderModel::accept(['id'=>$order['id'],'skill_id'=>$order['skill_id']]);
                    break;
                case 3:
                    OrderModel::go(['id'=>$order['id']]);
                    break;
                case 4:
                    OrderModel::reach(['id'=>$order['id']]);
                    break;
                case 5:
                    OrderModel::skillStart(['id'=>$order['id']]);
                    break;
                case 6:
                    OrderModel::skillFinish(['id'=>$order['id']]);
                    break;
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('订单状态更新失败',$e->getMessage());
        }
        $this->success('订单状态已更新');
    }


    public function refund($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->is_service == 2 && $this->error('请勿重复取消');
        if($this->request->isPost()){
            $params = $this->request->post('row/a');
            $actTravelPrice = sprintf("%.2f",$params['act_travel_price']);
            $refundPrice = sprintf("%.2f",$params['refund_price']);
            !in_array($row->paytype,[0,4]) && $this->error('当前支付方式无法进行退款');
            $totalPrice = sprintf("%.2f",$refundPrice);
            $allPrice = bcadd($actTravelPrice,$refundPrice,2);
            $allPrice>$row->payprice && $this->error('退款总额不能超过支付总额');
            $settlePrice = bcsub(($row->payprice-$actTravelPrice),$refundPrice,2);
            if($row->paytype == 0){
                $refund = new Refund();
                $re = $refund->wxRefund(['out_trade_no'=>$row->orderId,'transaction_id'=>$row->trade_no,'order_price'=>$row->payprice,'refund_price'=>$totalPrice]);
                $re != 'SUCCESS' && $this->error('无法进行微信退款,请联系管理员');
            }elseif($row->paytype == 5){
                \app\api\model\service\User::give_money(+$totalPrice,$row->user_id,'订单取消退款');
            }else{
                \app\api\model\service\User::money(+$totalPrice,$row->user_id,'订单取消退款');
            }
            $settleDay = $row->shop_id?\app\api\model\service\Shop::getSettleDay($row->shop_id):\app\api\model\service\ProjectConfig::getProjectConfig('settle_day');
            $settletime = $settleDay*86400+time();
            $update = ['is_service'=>2,'finishtime'=>time(),'is_settle'=>1,'act_travel_price'=>$actTravelPrice,'refund_price'=>$refundPrice,'settle_price'=>$settlePrice,'settletime'=>$settletime];
            if($row->skill_id)
            {
                $update['skill_percent'] = \app\admin\model\service\skill\Skill::where('id',$row->skill_id)->value('percent');
            }
            if($row->shop_id)
            {
                $update['shop_percent'] = \app\admin\model\service\shop\Shop::where('id',$row->shop_id)->value('percent');
            }
            $this->model->where('id',$params['id'])->update($update);
            db('service_order_log')->insert(['order_id'=>$ids,'user_id'=>$row->user_id,'type'=>9,'content'=>'平台已取消订单','createtime'=>time()]);
            $refundExist = \app\admin\model\service\order\Refundorder::where('order_id',$params['id'])->value('id');
            if($refundExist)
            {
                \app\admin\model\service\order\Refundorder::where('order_id',$params['id'])->update(['state'=>1]);
            }
            $userOpenid = \app\api\model\service\UserInfo::getOpenid($row->user_id,0);
            OrderModel::createRefundTemplateParams(['id'=>$row->id,'state'=>1,'type'=>0,'templateAttr'=>'user_sales_template','openid'=>$userOpenid,'note'=>'已退款']);
            // 退佣金
            $commissionOrder = \addons\shopro\model\commission\Order::get(['order_id' => $params['id']]);
            if ($commissionOrder) {
                (new RewardLibrary())->backCommissionRewardByOrder('refund', $commissionOrder);
            }
            $this->success('已退款');
        }
        $detail = db('service_order_detail')->field('name,image,sku_name,num,price,sumprice')->where('order_id',$ids)->find();
        $addList = db('service_add_order_detail')->field('name,cost_seconds,num,price')->where(['order_id'=>$ids])->select();
        $this->assign(['id'=>$ids,'row'=>$row,'detail'=>$detail,'addList'=>$addList]);
        return $this->view->fetch();
    }


}
